<?php

namespace App\Rules;

use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;

class ValidUrl implements Rule
{

    private $client;
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * @param string $attribute
     * @param mixed  $value
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function passes($attribute, $value)
    {
        $response = $this->client->request('HEAD', $value, [
            'allow_redirects' => false,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
                'Origin'     => 'https://detail.1688.com',
            ]
        ]);
        $code = $response->getStatusCode();
        if ($code != 200)
            return false;
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute ַis not a valid url';
    }

    /**
     * 获取实例
     * @return mixed
     */
    public static function instance()
    {
        return resolve(static::class);
    }
}
